<template>
  <el-form
    ref="formRef"
    :model="formData"
    :rules="formRules"
    v-loading="formLoading"
    label-width="0px"
    :inline-message="true"
  >
    <el-table :data="formData" class="-mt-10px">
      <el-table-column label="序号" type="index" width="100" />
       <el-table-column label="子件编码" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.inventoryId`" :rules="formRules.required" class="mb-0px!">
            <el-select
v-model="row.inventoryCode" placeholder="请选择存货编码" :disabled="props.isDisabled" 
              clearable remote reserve-keyword  
             filterable :loading="selectLoading" :remote-method="remoteInventory"
             @change="handleInventoryChange($event, row)">
              <el-option
                v-for="item in inventoryList"
                :key="item.id"
                :label="item.code"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </template>
      </el-table-column>

      <el-table-column label="子件名称" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.inventoryId`" :rules="formRules.required" class="mb-0px!">
            <el-select
v-model="row.inventoryName" placeholder="请选择存货编码" :disabled="props.isDisabled" 
              clearable remote reserve-keyword  
             filterable :loading="selectLoading" :remote-method="remoteInventory"
             @change="handleInventoryChange($event, row)"
             >
              <el-option
                v-for="item in inventoryList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="数量" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.qty`" :rules="formRules.required" class="mb-0px!">
            <el-input v-model="row.qty" placeholder="请输入数量" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="损耗比例" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.losrate`" :rules="formRules.required" class="mb-0px!">
            <el-input v-model="row.losrate" placeholder="请输入损耗比例" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="备注" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.cbmemo`" class="mb-0px!">
            <el-input v-model="row.cbmemo" placeholder="请输入备注" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column align="center" fixed="right" label="操作" width="60">
        <template #default="{ $index }">
          <el-button @click="handleDelete($index)" link>—</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-form>
  <el-row justify="center" class="mt-3">
    <el-button @click="handleAdd" round>+ 添加BOM子</el-button>
  </el-row>
</template>
<script setup lang="ts">
import { BomApi } from '@/api/wms/bom'
import {InventoryVO, InventoryApi} from "@/api/wms/inventory";
const selectLoading = ref(false) // 下拉框的加载中

const props = defineProps<{
  pid: undefined // 主表ID（主表的关联字段）
}>()
const formLoading = ref(false) // 表单的加载中
const formData = ref([])
const formRules = reactive({
  required: [{ required: true, message: '不能为空', trigger: 'blur' }],
})
const inventoryList = ref<InventoryVO[]>([]) // 存货数据

const formRef = ref() // 表单 Ref
/** 查询存货 */
const remoteInventory = (query: string) => {
  if (query) {
    selectLoading.value = true
    setTimeout(async () => {
      selectLoading.value = false
      inventoryList.value = await InventoryApi.getInventorySimpleList(query)
    }, 200)
  } else {
    setTimeout(async () => {
      const data = await InventoryApi.getInventoryPage({})
      inventoryList.value = data.list
    }, 100)
  }
}

watch(
  () => props.pid,
  async (val) => {
    // 1. 重置表单
    formData.value = []
    // 2. val 非空，则加载数据
    if (!val) {
      return;
    }
    try {
      formLoading.value = true
      const initialData  = await BomApi.getBomsListByPid(val)
      formData.value = await Promise.all(initialData.map(async (item) => {
        if (item.inventoryId) {
          const inventory = await InventoryApi.getInventory(item.inventoryId);
         
          return {
            ...item,
            inventoryName: inventory.name,
            inventoryCode: inventory.code,
            inventoryUnitName: inventory.unitName,
            inventorySpecModel: inventory.specModel,
            itax: inventory.taxRate,

          };
         
        }
      
        return item;
      
      }));

    } finally {
      formLoading.value = false
    }
  },
  { immediate: true }
)


/** 新增按钮操作 */
const handleAdd = () => {
  const row = {
    id: undefined,
    pid: undefined,
    cinvcode: undefined,
    qty: undefined,
    losrate: undefined,
    cbmemo: undefined,
  }
  row.pid = props.pid
  formData.value.push(row)
}

/** 删除按钮操作 */
const handleDelete = (index) => {
  formData.value.splice(index, 1)
}

/** 表单校验 */
const validate = () => {
  return formRef.value.validate()
}

/** 表单值 */
const getData = () => {
  return formData.value
}

/** 处理存货编码选择变化 */
const handleInventoryChange = (value, row) => {
  const selectedInventory = inventoryList.value.find(item => item.id === value);
  if (selectedInventory) {

    row.inventoryId = selectedInventory.id;
    row.inventoryName = selectedInventory.name;
    row.inventoryCode = selectedInventory.code;
    row.inventoryUnitName = selectedInventory.unitName;
  }
};

defineExpose({ validate, getData })
</script>